package handle

import (
	g "blog.wuzhispace.com/internal/global"
	"blog.wuzhispace.com/internal/model"
	"github.com/gin-gonic/gin"
)

type Link struct {
}

// AddOrEditLinkReq 添加或修改友链
type AddOrEditLinkReq struct {
	ID      int    `json:"id"`
	Name    string `json:"name" binding:"required"`
	Avatar  string `json:"avatar"`
	Address string `json:"address" binding:"required"`
	Intro   string `json:"intro"`
}

// GetList 是 Link 结构体的一个方法，用于获取链接列表
// 参数 c 是一个 gin.Context 实例，用于处理 HTTP 请求
func (l Link) GetList(c *gin.Context) {
	var query PageQuery
	if err := c.ShouldBindJSON(&query); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}
	data, total, err := model.GetLinkList(GetDB(c), query.Page, query.Size, query.Keyword)
	if err != nil {
		ReturnError(c, g.ErrDbOp, err)
		return
	}
	ReturnSuccess(c, PageResult[model.FriendLink]{
		List:  data,
		Total: total,
		Page:  query.Page,
		Size:  query.Size,
	})
}

func (l Link) SaveOrUpdate(c *gin.Context) {
	var req AddOrEditLinkReq
	if err := c.ShouldBindJSON(&req); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}
	link, err := model.SaveOrUpdateLink(GetDB(c), req.ID, req.Name, req.Avatar, req.Address, req.Intro)
	if err != nil {
		ReturnError(c, g.ErrDbOp, err)
		return
	}
	ReturnSuccess(c, link)
}
func (l Link) Delete(c *gin.Context) {
	var ids []int
	if err := c.ShouldBindJSON(&ids); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}
	result := GetDB(c).Delete(&model.FriendLink{}, "id in ?", ids)
	if result.Error != nil {
		ReturnError(c, g.ErrDbOp, result.Error)
		return
	}
	ReturnSuccess(c, result.RowsAffected)
}
